/* 
根据实际高度将html content拆分成独立的块
执行前要保证父级及以上没有滚动，否则取位置不准
*/
export default async function setBlocks(el,options) {
    /* 
    @params
    el              element
    options         配置参数{papeHeight:600}
    */
    const { 
        papeHeight,
        separatorHeight,
    } = Object.assign({
        papeHeight: 600,
        separatorHeight:50,//分隔块高度
    }, options || {});
    
    const allHeight = getElHeight(el);
    if (allHeight <= papeHeight) {
        // 不需要拆分
        return null;
    }
    // 当前计算的页面数量
    let pageNum = 1;
    console.log('分页开始')
    pageNum = await setHtml(el, { pageNum, papeHeight, separatorHeight });
    console.log('分页完成')
    return {
        papeHeight,
        separatorHeight,
        pageNum,
    };
}
const getElHeight = (el) => {
    const height = el.offsetHeight || el.clientHeight;
    return height;
}
const getElMaginBottom = (el) => {
    const style = getComputedStyle(el);
    return Number(style.marginBottom) || 0;
}
const setPageBottom = (el,sHeight) => {
    const style = getComputedStyle(el);
    el.style.marginBottom = (parseInt(style.marginBottom || 0,10) + sHeight)+'px';
}
const createSeparatEl = (top) => {
    const myHeight = 25;
    const div = document.createElement('div');
    div.style.height = myHeight + 'px';
    div.style.position = 'absolute';
    div.style.top = (top - myHeight / 2) + 'px';
    div.style.backgroundColor = '#eee';
    div.style.left = '0';
    div.style.width = '100%';
    // div.style.boxShadow = '0 0 5px rgba(0,0,0,0.5)';
    return div;
}
const addSeparator = (el, { bottom = 0 }) => {
    return new Promise((ok, fail) => {
        const div = createSeparatEl(bottom);
        el.append(div);
        setTimeout(ok, 0)
    })
}
function countTextLines(element) {
    // 获取元素的样式
    const styles = getComputedStyle(element);

    // 获取元素的高度和行高
    const height = parseFloat(styles.height);
    const lineHeight = parseFloat(styles.lineHeight);

    // 计算行数
    const lineCount = Math.ceil(height / lineHeight);

    return lineCount;
}
function getLineHeight(el) {
    const styles = getComputedStyle(el);
    var lineHeight = styles.lineHeight;

    if (lineHeight === "normal") {
        var fontSize = parseFloat(styles.fontSize);
        return fontSize * 1.2; // 默认的行高是字体大小的1.2倍
    } else if (lineHeight.includes("px")) {
        return parseFloat(lineHeight);
    } else if (lineHeight.includes("em")) {
        var fontSize = parseFloat(styles.fontSize);
        return fontSize * parseFloat(lineHeight);
    } else if (lineHeight.includes("%")) {
        var parentLineHeight = parseFloat(window.getComputedStyle(el.parentElement).lineHeight);
        return parentLineHeight * (parseFloat(lineHeight) / 100);
    } else {
        return parseFloat(lineHeight);
    }
}
// 获取第n行的最后一个字符的下标
function getLastCharIndexInNthLine(div, targetLineCount) {
    console.log('------- getLastCharIndexInNthLine')
    console.log('待截取行数', targetLineCount)
    const divRect = div.getBoundingClientRect();
    const styles = window.getComputedStyle(div);
    // 获取div的文本内容
    const content = div.innerHTML;
    // 创建一个隐藏的div，用于计算每行文本的宽度
    const hiddenDiv = document.createElement('div');
    hiddenDiv.style.visibility = 'hidden';
    hiddenDiv.style.position = 'absolute';
    hiddenDiv.style.fontSize = styles.fontSize;
    hiddenDiv.style.fontWeight = styles.fontWeight;
    hiddenDiv.style.fontFamily = styles.fontFamily;
    hiddenDiv.style.padding = styles.padding;
    hiddenDiv.style.width = styles.width;
    hiddenDiv.style.textAlign = styles.textAlign;
    document.body.appendChild(hiddenDiv);

    let currentLine = 0; // 当前行数
    let lastCharIndex = 0; // 最后一个字符的下标
    let currentHeight = hiddenDiv.getBoundingClientRect().height;
    /* let findIdx = 0;
    while (findIdx < content.length) {
        let word = _get
    } */
    for (let i = 0; i < content.length; i++) {
        // 将字符添加到隐藏的div中
        hiddenDiv.innerHTML += content[i];
        // 获取当前行的宽度
        const lineHeight = hiddenDiv.getBoundingClientRect().height;
        // 如果宽度超过div的宽度，则表示已经换行
        if (lineHeight > currentHeight) {
            console.log(`高度变化${currentHeight}/${lineHeight}`)
            currentHeight = lineHeight;
            currentLine++;
            // 如果已经到达第n行，则记录下最后一个字符的下标
            console.log(`行变化${currentLine}/${targetLineCount}`)
            if (currentLine === targetLineCount) {
                lastCharIndex = i - 1;
                // 重置隐藏的div的文本内容
                hiddenDiv.innerHTML = '';
                break;
            }
        }
    }

    // 删除隐藏的div
    document.body.removeChild(hiddenDiv);
    console.log('最后字符', lastCharIndex)

    return lastCharIndex;
}
const getDNumByLineheight = (el, d) => {
    /* 
    计算根据行高纠正截取数值
    */
    // 获取元素的样式
    const lineHeight = getLineHeight(el);
    // console.log('行高',lineHeight)
    const lineCount = Math.floor(d / lineHeight);
    const lastCharIndex = getLastCharIndexInNthLine(el, lineCount);
    // console.log(lastCharIndex)
    return {
        height: lineCount * lineHeight,
        lineCount,
        lastCharIndex: lastCharIndex
    };
}
const copyEl = (el, options) => {
    const newEl = el.cloneNode(true);
    const {
        height,
        isRetainBottom = false,
    } = options || {};
    if (height) {
        newEl.style.height = `${height}px`;
        newEl.style.overflowY = 'hidden';
    }
    
    if (isRetainBottom) {
        // el.style.position = 'relative';
        // newEl.style.position = 'absolute';
        // newEl.style.bottom = '0';
        // newEl.style.left = '0';
    }
    return newEl;
}
function part1Full(allText, div, { currentTextLen, width,fontSize=20 }) {
    const testDiv = document.createElement('div');
    testDiv.style.whiteSpace = 'nowrap';
    div.append(testDiv);
    const rect = testDiv.getBoundingClientRect();
    if (width - rect.right > fontSize) {
        const _dText = allText.str(currentTextLen + 1).trim();
        let idx = _dText.indexOf(' ');
        const newWord = _dText.substring(0, idx - 1);
        currentTextLen = allText.indexOf(newWord, currentTextLen + 1) + newWord.length;
    }
    return currentTextLen;
}
function splitParagraph(childEl, lastIndex, separatorHeight) {
    const rect = childEl.getBoundingClientRect();

    const part1_div = document.createElement('div');
    const part2_div = document.createElement('div');

    const sepa = document.createElement('div');
    sepa.style.height = (separatorHeight * 2) + 'px';

    const allText = childEl.innerHTML;
    let part1_str_len = lastIndex+1;
    part1_div.innerHTML = allText.substr(0, part1_str_len);
    part2_div.innerHTML = allText.substr(part1_str_len);

    childEl.innerHTML = '';
    childEl.append(part1_div);

    childEl.append(sepa);
    childEl.append(part2_div);
    return part2_div;
}
/* function splitParagraph(childEl, splitHeight, separatorHeight) {
    const rect = childEl.getBoundingClientRect();
    const part1_div = copyEl(childEl, { height: rect.height - splitHeight });
    const part2_div = copyEl(childEl);

    const sepa = document.createElement('div');
    sepa.style.height = (separatorHeight*2) + 'px';

    const part2_container = document.createElement('div');
    part2_container.append(part2_div);
    part2_container.style.position = 'relative';
    part2_container.style.overflowY = 'hidden';
    part2_container.style.height = splitHeight + 'px';
    part2_div.style.position = 'absolute';
    part2_div.style.bottom = '0';
    part2_div.style.left = '0';

    childEl.innerHTML = '';
    childEl.append(part1_div);
    childEl.append(sepa);
    childEl.append(part2_container);
} */
const setHtml = (el, { papeHeight, pageNum, separatorHeight }) => {
    return new Promise(async (ok, fail) => {
        let childIdx = 0, childLen = el.children.length, sumHeight = 0;
        while (childIdx < childLen) {
            // console.log('index',childIdx)
            const childEl = el.children[childIdx];
            const rect = childEl.getBoundingClientRect();
            sumHeight += rect.height;
            if (sumHeight >= papeHeight) {
                // 分块
                const d = sumHeight - papeHeight;
                // console.log(d)
                if (d === 0) {
                    // 按段分
                    const el_up = el.children[childIdx - 1];
                    const rectUp = el_up.getBoundingClientRect();
                    setPageBottom(el_up, separatorHeight);
                    await addSeparator(el, { bottom: rectUp.bottom + separatorHeight });
                    sumHeight = 0;
                } else {
                    // 拆段落
                    const lineObj = getDNumByLineheight(childEl, d);
                    const part2Div = splitParagraph(childEl, lineObj.lastCharIndex,separatorHeight);
                    // splitParagraph(childEl, round_d,separatorHeight);
                    const part2Rect = part2Div.getBoundingClientRect();
                    const rect = childEl.getBoundingClientRect();
                    await addSeparator(el, { bottom: rect.bottom - part2Rect.height - separatorHeight });
                    sumHeight = lineObj.height;// round_d
                    console.log(`第${pageNum}页追加内容，当前高度${sumHeight}/${papeHeight}`)
                    childIdx += 1;
                }
                pageNum += 1;
            } else {
                console.log(`第${pageNum}页追加内容，当前高度${sumHeight}/${papeHeight}`)
                childIdx += 1;
            }
        }
        ok(pageNum);
    });
}